package com.dms.modules.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dms.common.exception.BusinessException;
import com.dms.modules.product.dto.ProductSkuDTO;
import com.dms.modules.product.entity.ProductSku;
import com.dms.modules.product.mapper.ProductSkuMapper;
import com.dms.modules.product.service.ProductSkuService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@Service
public class ProductSkuServiceImpl extends ServiceImpl<ProductSkuMapper, ProductSku> implements ProductSkuService {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public List<ProductSku> getByProductId(Long productId) {
        if (productId == null) {
            throw new BusinessException("商品ID不能为空");
        }
        
        LambdaQueryWrapper<ProductSku> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductSku::getProductId, productId)
               .eq(ProductSku::getStatus, 1)
               .orderByAsc(ProductSku::getId);
        return list(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveBatch(List<ProductSku> skuList) {
        if (skuList == null || skuList.isEmpty()) {
            return true;
        }
        return super.saveBatch(skuList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteByProductId(Long productId) {
        if (productId == null) {
            throw new BusinessException("商品ID不能为空");
        }
        
        LambdaQueryWrapper<ProductSku> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductSku::getProductId, productId);
        return remove(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateStock(Long skuId, Integer quantity) {
        if (skuId == null) {
            throw new BusinessException("SKU ID不能为空");
        }
        if (quantity == null) {
            throw new BusinessException("数量不能为空");
        }
        
        ProductSku sku = getById(skuId);
        if (sku == null) {
            throw new BusinessException("SKU不存在");
        }
        
        // 检查库存是否足够
        if (quantity < 0 && sku.getStock() < Math.abs(quantity)) {
            throw new BusinessException("库存不足");
        }
        
        sku.setStock(sku.getStock() + quantity);
        return updateById(sku);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean create(ProductSkuDTO skuDTO) {
        try {
            // 如果没有提供SKU编码，则自动生成
            if (skuDTO.getSkuCode() == null || skuDTO.getSkuCode().trim().isEmpty()) {
                // 生成SKU编码：SKU + 商品ID + 3位随机数
                String randomCode = String.format("%03d", (int) (Math.random() * 1000));
                String skuCode = "SKU" + skuDTO.getProductId() + randomCode;
                skuDTO.setSkuCode(skuCode);
            }
            
            // 检查SKU编码是否已存在
            if (existsSkuCode(skuDTO.getSkuCode(), null)) {
                throw new BusinessException("SKU编码已存在");
            }
            
            ProductSku sku = new ProductSku();
            BeanUtils.copyProperties(skuDTO, sku);
            
            // 将 Map 转换为 JSON 字符串
            if (skuDTO.getSpecValues() != null) {
                sku.setSpecValues(objectMapper.writeValueAsString(skuDTO.getSpecValues()));
            }
            
            // 设置默认值
            if (sku.getStatus() == null) {
                sku.setStatus(1); // 默认启用
            }
            if (sku.getSales() == null) {
                sku.setSales(0); // 默认销量为0
            }
            
            return save(sku);
        } catch (Exception e) {
            log.error("创建SKU失败", e);
            throw new BusinessException("创建SKU失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(ProductSkuDTO skuDTO) {
        if (skuDTO.getId() == null) {
            throw new BusinessException("SKU ID不能为空");
        }
        
        // 检查SKU是否存在
        ProductSku sku = getById(skuDTO.getId());
        if (sku == null) {
            throw new BusinessException("SKU不存在");
        }
        
        // 检查SKU编码是否已存在
        if (existsSkuCode(skuDTO.getSkuCode(), skuDTO.getId())) {
            throw new BusinessException("SKU编码已存在");
        }
        
        BeanUtils.copyProperties(skuDTO, sku);
        return updateById(sku);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateStatus(List<Long> skuIds, Integer status) {
        if (skuIds == null || skuIds.isEmpty()) {
            throw new BusinessException("SKU ID列表不能为空");
        }
        if (status == null) {
            throw new BusinessException("状态不能为空");
        }
        
        LambdaQueryWrapper<ProductSku> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(ProductSku::getId, skuIds);
        
        ProductSku sku = new ProductSku();
        sku.setStatus(status);
        
        return update(sku, wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updatePrices(Map<Long, BigDecimal> skuPriceMap) {
        if (skuPriceMap == null || skuPriceMap.isEmpty()) {
            throw new BusinessException("价格映射不能为空");
        }
        
        for (Map.Entry<Long, BigDecimal> entry : skuPriceMap.entrySet()) {
            ProductSku sku = getById(entry.getKey());
            if (sku == null) {
                throw new BusinessException("SKU不存在: " + entry.getKey());
            }
            if (entry.getValue().compareTo(BigDecimal.ZERO) <= 0) {
                throw new BusinessException("价格必须大于0: " + entry.getKey());
            }
            
            sku.setPrice(entry.getValue());
            updateById(sku);
        }
        
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateStocks(Map<Long, Integer> skuStockMap) {
        if (skuStockMap == null || skuStockMap.isEmpty()) {
            throw new BusinessException("库存映射不能为空");
        }
        
        for (Map.Entry<Long, Integer> entry : skuStockMap.entrySet()) {
            ProductSku sku = getById(entry.getKey());
            if (sku == null) {
                throw new BusinessException("SKU不存在: " + entry.getKey());
            }
            if (entry.getValue() < 0) {
                throw new BusinessException("库存不能小于0: " + entry.getKey());
            }
            
            sku.setStock(entry.getValue());
            updateById(sku);
        }
        
        return true;
    }

    @Override
    public IPage<ProductSku> pageSkus(Page<ProductSku> page, Long productId, Integer status) {
        LambdaQueryWrapper<ProductSku> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(productId != null, ProductSku::getProductId, productId)
               .eq(status != null, ProductSku::getStatus, status)
               .orderByDesc(ProductSku::getCreateTime);
        
        return page(page, wrapper);
    }

    @Override
    public boolean existsSkuCode(String skuCode, Long excludeId) {
        if (skuCode == null) {
            return false;
        }
        
        LambdaQueryWrapper<ProductSku> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductSku::getSkuCode, skuCode);
        if (excludeId != null) {
            wrapper.ne(ProductSku::getId, excludeId);
        }
        
        return count(wrapper) > 0;
    }
} 